import React, { useState } from 'react';
import { Card, Form, Input, Button, Space, message, Select, Switch } from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { history } from '@umijs/max';

import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import type { UserRequest } from '@/services/generated';

const { Option } = Select;

const UserCreate: React.FC = () => {
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);

  // 创建用户
  const handleSubmit = async (values: UserRequest & { password: string; password_confirm: string }) => {
    try {
      setSubmitting(true);
      await autoLoginInDev();
      await apiClients.users.usersCreate({ 
        userRequest: values 
      });
      message.success('用户创建成功');
      history.push('/user/list');
    } catch (error: any) {
      console.error('创建用户失败:', error);
      // API中间件已经处理了错误显示
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <PageContainer
      title="新增用户"
      extra={
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => history.back()}
        >
          返回
        </Button>
      }
    >
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            status: 'active',
            is_staff: false,
            is_superuser: false,
            is_active: true,
          }}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名!' },
              { min: 3, message: '用户名至少3个字符!' },
            ]}
          >
            <Input placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱!' },
              { type: 'email', message: '请输入有效的邮箱地址!' },
            ]}
          >
            <Input placeholder="邮箱地址" />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码!' },
              { min: 8, message: '密码至少8个字符!' },
            ]}
          >
            <Input.Password placeholder="密码" />
          </Form.Item>

          <Form.Item
            name="password_confirm"
            label="确认密码"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码!' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致!'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="确认密码" />
          </Form.Item>

          <Form.Item
            name="real_name"
            label="真实姓名"
          >
            <Input placeholder="真实姓名" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="手机号"
          >
            <Input placeholder="手机号" />
          </Form.Item>

          <Form.Item
            name="status"
            label="用户状态"
            rules={[{ required: true, message: '请选择用户状态!' }]}
          >
            <Select placeholder="请选择用户状态">
              <Option value="active">激活</Option>
              <Option value="inactive">未激活</Option>
              <Option value="suspended">暂停</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="department_id"
            label="部门ID"
          >
            <Input placeholder="部门ID（可选）" type="number" />
          </Form.Item>

          <Form.Item
            name="is_active"
            label="账户激活"
            valuePropName="checked"
          >
            <Switch checkedChildren="激活" unCheckedChildren="禁用" />
          </Form.Item>

          <Form.Item
            name="is_staff"
            label="管理员权限"
            valuePropName="checked"
          >
            <Switch checkedChildren="是" unCheckedChildren="否" />
          </Form.Item>

          <Form.Item
            name="is_superuser"
            label="超级管理员"
            valuePropName="checked"
          >
            <Switch checkedChildren="是" unCheckedChildren="否" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={submitting}
                icon={<SaveOutlined />}
              >
                创建用户
              </Button>
              <Button onClick={() => history.back()}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default UserCreate;
